﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BallotCounter.Question;

namespace BallotCounter.Answer
{
    class Bob : IBallotCounter
    {
        public int BallotCount(int[] ballotArray)
        {
            if (ballotArray.Length == 0)
            {
                return -1;
            }
            else if (ballotArray.Where(v => v < 0).Count() > 0)
            {
                return -1;
            }
            else if (ballotArray.Length == 1)
            {
                return ballotArray[0];
            }
            else
            {
                Array.Sort(ballotArray);
                KeyValuePair<int, int>[] res = new KeyValuePair<int, int>[2];
                res[0] = new KeyValuePair<int, int>(int.MinValue, int.MinValue);
                res[1] = new KeyValuePair<int, int>(int.MinValue, int.MinValue);

                int cur = int.MinValue;
                int cnt = int.MinValue;

                for (int i = 0; i < ballotArray.Length; i++)
                {
                    if (cur != ballotArray[i])
                    {
                        InsertHeap(res, cur, cnt);
                        cur = ballotArray[i];
                        cnt = 1;
                    }
                    else if (i == ballotArray.Length - 1)
                    {
                        InsertHeap(res, cur, cnt + 1);
                    }
                    else
                    {
                        cnt++;
                    }

                }
                if (res[0].Value == res[1].Value)
                {
                    return -1;
                }
                else
                {
                    return res[1].Key;
                }
            }            


        }

        private void InsertHeap(KeyValuePair<int, int>[] res, int cur, int cnt)
        {
            KeyValuePair<int, int> curKVP = new KeyValuePair<int, int>(cur, cnt);

            if (res[0].Value < curKVP.Value)
            {
                res[0] = curKVP;
            }

            if (res[1].Value < curKVP.Value)
            {
                KeyValuePair<int, int> tmp = res[1];
                res[1] = curKVP;
                res[0] = tmp;
            }
        }
    }
}
